package com.demo.servlet.demo1215;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.junit.Test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JsonTest {
    //1.javaBean 和 JSON 互转
    @Test
    public void test01() {
        Student student = new Student(1, "张三", 18, "清华大学");
        //创建 Gson 对象
        Gson gson = new Gson();
        //toJson() : 把 Java 对象 转成 JSON 字符串
        String studentStr = gson.toJson(student);
        System.out.println(studentStr);
        //fromJson() : 把 JSON 字符串 转成 Java 对象
        Student student1 = gson.fromJson(studentStr, Student.class);
        System.out.println(student1);
    }

    //2.List 和 JSON 互转
    @Test
    public void test02() {
        List<Student> students = new ArrayList<>();
        for (int i = 1; i <= 10; i++) {
            students.add(new Student(i, "学生" + i, i + 18, "实验小学"));
        }
        Gson gson = new Gson();
        //List 对象转换成 JSON 字符串
        String studentsStr = gson.toJson(students);
        System.out.println(studentsStr);
        //JSON 字符串 转换成 List 对象
        List<Student> studentList = gson.fromJson(studentsStr, new TypeToken<List<Student>>() {
        }.getType());
        System.out.println(studentList);
    }

    //3.Map 和 JSON 互转
    @Test
    public void test03() {
        Map<Integer, Student> studentMap = new HashMap<>();
        for (int i = 1; i <= 10; i++) {
            studentMap.put(i, new Student(i, "学生" + i, i + 18, "实验小学"));
        }
        Gson gson = new Gson();
        //Map 对象转换成 JSON 字符串
        String studentsStr = gson.toJson(studentMap);
        System.out.println(studentsStr);
        //JSON 字符串 转换成 Mao 对象
        Map<Integer, Student> studentMap1 = gson.fromJson(studentsStr, new TypeToken<Map<Integer, Student>>() {
        }.getType());
        System.out.println(studentMap1);
    }
}
